<?php
namespace app\index\Controller;

use app\common\controller\Base;
use app\common\model\Cate;
use app\common\model\User;
use app\common\model\Comment;
use app\common\model\Collection;
use app\common\model\Article as ArticleModel;
use think\facade\Request;
use think\Db;

class Article extends Base
{
	//文章分类
    public function cate(){

		$where =[];
		//获取分类ID
		$ename = Request::param('ename');
		//halt($cateename);
		
		//如果存在这个分类
		if($ename){
			$cate = Cate::where('ename',$ename)->find();
				if($cate){
					$where = [
						'cate_id' => $cate['id']
					];
				} else {
					return $this->error('没有此类目','index/article/cate');
				}
		} 
		
		$types = input('type');
		switch ($types) {
				//查询文章,10个分1页
                case 'all':
				$artList = ArticleModel::withCount('user,cate,comments')->where('status',1)->where($where)->order(['is_top'=>'desc','create_time'=>'desc'])->paginate(10);
				break;
				
				case 'hot':
				$artList = ArticleModel::withCount('user,cate,comments')->where('status',1)->where($where)->where('is_hot',1)->order(['is_top'=>'desc','create_time'=>'desc'])->paginate(10);
				break;
				
				case 'top':
				$artList = ArticleModel::withCount('user,cate,comments')->where('status',1)->where($where)->where('is_top',1)->order(['is_top'=>'desc','create_time'=>'desc'])->paginate(10);
				break;
				
				default:
				$artList = ArticleModel::withCount('user,cate,comments')->where('status',1)->where($where)->order(['is_top'=>'desc','create_time'=>'desc'])->paginate(10);			
				
		}
		$this->assign('type', $types);
		$this->assign('artList',$artList);
		//	热议文章
		$artHot = ArticleModel::withCount('comments')->where('status',1)->whereTime('create_time', 'year')->order('comments_count','desc')->limit(10)->select();
		$this->assign('artHot',$artHot);

		return $this->fetch();
    }
	
	public function pagedata(){
        //获取总条数
       $list = User::all(); 
       $count=count($list);
       //获取每页显示的条数
       $limit= Request::instance()->param('limit');
       //获取当前页数
       $page= Request::instance()->param('page');
       //计算出从那条开始查询
       $tol=($page-1)*$limit+1;
       // 查询出当前页数显示的数据
       $list = User::where('id','>=',$tol)->limit($limit)->select()->toArray();
       //返回数据
       return ["code"=>"0","msg"=>"","count"=>$count,"data"=>$list];
    }

	//文章详情页
    public function detail()
    {
		//获取文章ID
		$artId = Request::param('id');
		//查询文章
		$article = ArticleModel::withCount('user,cate,comments')->find($artId);
		if($article){
		$article->setInc('pv');	
		} else {
			return $this->error('无此帖子','index/index/index');
		}
		$this->assign('article',$article);

		//统计评论
		//$articleCount = $article['comments']->count();
		//$this->assign('articleCount',$articleCount);
		
		
		//	热议文章
		$artHot = ArticleModel::withCount('comments')->where('status',1)->whereTime('create_time', 'year')->order('comments_count','desc')->limit(10)->select();
		$this->assign('artHot',$artHot);
			
		return view();
    }
	
	//文章评论
	public function comment()
	{
		//if (Request::isAjax()){
		//获取评论
		//$data = Request::post();
		$data = [
                'content' => input('post.content'),
                'article_id' => input('post.article_id'),
                'user_id' => input('post.user_id')
            ];

		//用户留言存入数据库
		if (Comment::create($data,true)) {
			return ['code'=>1, 'msg'=>'留言成功'];
		} else{
			return ['code'=>0, 'msg'=>'留言失败'];
		}
	}
	
	

    //添加文章
    public function add()
	{
		$this->isLogin();
		if(Request::isAjax()){
		$data = Request::post();
		
		$validate = new \app\common\validate\Article(); //调用验证器
		$res = $validate->scene('Artadd')->check($data); //进行数据验证		
			if(true !==$res)
			{	
			//echo '<script>alert("'.$res.'");location.back()</script>';
			return $this->error($validate->getError());
			} else {	
				$result = model('Article')->add($data);
				if($result == 1) {
				$this->success('文章添加成功！','index/index/index');
				} else {
				$this->error($result);
				}
			}
		}
		return view();
    }

    //编辑文章
    public function edit()
    {
		$this->isLogin();
		if(Request::isAjax()){
		$data = Request::post();
		$validate = new \app\common\validate\Article(); //调用验证器
		$res = $validate->scene('Artadd')->check($data); //进行数据验证
			if(true !==$res)
			{	
			//echo '<script>alert("'.$res.'");location.back()</script>';
			return $this->error($validate->getError());
			} else 
			{	
				$result = model('Article')->edit($data);
				if($result == 1) {
				$this->success('文章修改成功！','index/user/post');
				} else {
				$this->error($result);
				}
			}
		}
        $article = ArticleModel::find(input('id'));
		$this->assign('article',$article);
		
		return $this->fetch();
    }
	
	//删除文章
    public function delete()
	{
		$article = ArticleModel::find(input('id'));
		$result = $article->delete();
		if($result) {
			$this->success('文章删除成功','index/user/post');
		} else {
			$this->error(文章删除失败);
			
		}
		return $res;
	}
	
	
	
	public function uploadImage1()
    {
	//thinkphp5的框架，如果是原生的，用$_FiLES['file']获取到图片，
        $file 	= request()->file('file');
        $info 	= $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
             $name_path =str_replace('\\',"/",$info->getSaveName());

                $result['data']["src"] = "/uploads/layui/".$name_path;
            $url 	= $info->getSaveName();
            //图片上传成功后，组好json格式，返回给前端
            $arr   = array(
                'code' => 0,
                'message'=>'',
                'data' =>array(
                    'src' => "/uploads/".$name_path
                    ),
                );
        }

        return json_encode($arr);

    }
	
	//添加文章和编辑页富文本编辑器图片上传
	public function lay_img_upload()
    {
        $file = Request()->file('file');
        if(empty($file)){
            $result["code"] = "1";
            $result["msg"] = "请选择图片";
            $result['data']["src"] = '';
        }else{
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move('uploads/' );
            if($info){
                $infos = $info->getInfo();
                // 源文件名
                $name = $infos['name'];
 
                $name_path =str_replace('\\',"/",$info->getSaveName());
                //成功上传后 获取上传信息
                $result["code"] = '0';
                $result["msg"] = "上传成功";
                $result['data']["src"] = "/uploads/".$name_path;
                $result['data']["title"] = $name;
            }else{
                // 上传失败获取错误信息
                $result["code"] = "2";
                $result["msg"] = "上传出错";
                $result['data']["src"] ='';
            }
        }
 
        return json_encode($result);
 
    }
	
	//文章评论富文本编辑器图片上传
	public function comment_img_upload()
    {
		$this->isLogin();
        $file = Request()->file('file');
        if(empty($file)){
            $res['status'] = "1";
            $res['msg'] = "请选择图片";
            $res['url'] = '';
        }else{
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move('uploads/' );
            if($info){
				$name = $info->getFilename();;
                $name_path =str_replace('\\',"/",$info->getSaveName());
                //成功上传后 获取上传信息
                $res['status'] = '0';
                $res['msg'] = "上传成功";
				$res["url"] = "/uploads/".$name_path;
                $res['title'] = $name;
            }else{
                // 上传失败获取错误信息
                $res['status'] = "2";
                $res['msg'] = "上传出错".$file->getError();
                $res['url'] ='';
            }
        }
 
        return ($res);
 
    }
	
	//文章收藏
	public function collection(){
		$data = Request::param();
		halt($data);
	}
	
	//文章置顶，状态
	public function jieset(){
		$data = Request::param();
		$article = ArticleModel::find($data['id']);
		if($data['field'] === 'top') {
			if($data['rank']==1){
				$article->save(['is_top' => 1]);
				$res['status'] = 0;
				$res['msg'] ='置顶成功';
			} else {
				$article->save(['is_top' => 0]);
				$res['status'] = 0;
				$res['msg'] ='已取消置顶';
			}
		} else {
			if($data['rank']==1){
				$article->save(['is_hot' => 1]);
				$res['status'] = 0;
				$res['msg'] ='已设精贴';
			} else {
				$article->save(['is_hot' => 0]);
				$res['status'] = 0;
				$res['msg'] ='精贴已取消';
			}
		}
		return json($res);	
		//halt($data);
	}


	
}